#ifndef __RTC_SERVER_H
#define __RTC_SERVER_H
#include <thread>
#include <queue>
#include <mutex>
#include <rtc_base/rtc_certificate.h>
#include "base/event_loop.h"
#include "xrtcserver_def.h"
namespace xrtc
{

    struct RtcServerOptions
    {
        int worker_num;
    };
    class RtcWorker;
    class RtcServer
    {

    public:
        enum
        {
            QUIT = 0,
            RTC_MSG = 1

        };
        RtcServer();
        ~RtcServer();
        int Init(const char *conf_file);
        bool Start();
        void Stop();
        void Join();
        int Notify(int msg);
        int SendRtcMsg(std::shared_ptr<RtcMsg>);
        void PushMsg(std::shared_ptr<RtcMsg>);
        std::shared_ptr<RtcMsg> PopMsg();
        const std::vector<RtcWorker *> &workers() { return workers_; };
        RtcWorker *GetWorker(const std::string &stream_name);
        RtcWorker *GetWorker(uint64_t uid);
        RtcWorker *GetWorkerById(int worker_id);

        int worker_num();
        friend void RtcServerRecvNotify(EventLoop *, IOWatcher *, int, int, void *);

    private:
        int ProcessNotify(int msg);
        void ProcessRtcMsg();
        void Stop_();
        int CreateWorker(int worker_id);

        int GenerateAndCheckCertificate();

    private:
        EventLoop *el_;
        RtcServerOptions options_;
        IOWatcher *pipe_watcher_ = nullptr;
        std::thread *thread_ = nullptr;
        int notify_recv_fd_ = -1;
        int notify_send_fd_ = -1;
        std::queue<std::shared_ptr<RtcMsg>> q_msg_;
        std::mutex q_msg_mtx_;
        std::vector<RtcWorker *> workers_;
        rtc::scoped_refptr<rtc::RTCCertificate> certificate_;
    };

} // namespace xrtc

#endif //__RTC_SERVER_H